var geologicHazardQueryDlg=null;
var global_del_control = null;
var newSketchDig = null;
var global_vector_layer =null;
var global_sketch_geoCode =null;
var global_sketch_geoCodeType = null;///灾点标识
var global_features_add = null;
var global_features_del = null;

function initSketchAddDlg(){
	if(geoHazardQueryForSketchQueryDlg){
		geoHazardQueryForSketchQueryDlg.close();
		geoHazardQueryForSketchQueryDlg =null;
	}
	if(sketchQueryDlg)
	{
		sketchQueryDlg.close();
		sketchQueryDlg =null;
	}
	global_features_add = new Array();
	global_features_del = new Array();
	if(global_vector_layer)
	{
		global_vector_layer.removeAllFeatures();
		global_vector_layer =null;
	}
	initGeologicHazardQueryDlg(); 
}

function initGeologicHazardQueryDlg(){
	if(geologicHazardQueryDlg)
		return;
	var geologicHazardDlgHtml = '<div style="width:340px;height:200px;font-size:11px;font-family:微软雅黑;position:absolute;left:15px;top:40px;">'+
												'<div id="yjdc3jbxxQueryConditionBar" style="position:absolute;left:0px;top:0px;width:340px;height:40px;">'+
												'<label>时间范围：</label><input id="yjdc3jbxxTimeInputForm" type="text" style="width:120px;height:18px;" class="Wdate" onfocus="WdatePicker({startDate: \'00:00:00\',dateFmt:\'yyyy-MM-dd HH:mm:ss\',alwaysUseStartDate:true})"/> '+
												' — <input id="yjdc3jbxxTimeInputTo" style="width:120px;height:18px;" type="text" class="Wdate" onfocus="WdatePicker({startDate:\'00:00:00\',dateFmt:\'yyyy-MM-dd HH:mm:ss\',alwaysUseStartDate:true})"/>'+
												'<br/>'+
												'<label>灾害名称：</label><input id="yjdc3jbxxNameInputTo" style="width:150px;height:15px;"/>'+
												'<input id="geohazardBtn" type="button" value="确定" />'+
												'</div>'+
												'<div id="queryYjdc3JbxxResultContent" style="width:330px;height:135px;border:1px solid #ABADB3;position:absolute;left:2px;top:55px;overflow-y:auto;overflow-x:hidden;">'+
												'<table id="queryYjdc3JbxxResultTable" style="font-size:11px;width:330px;border-collapse: collapse;">'+
													'<tr>'+
														'<td class="queryTd">序号</td><td class="queryTd">灾害名称</td><td class="queryTd">灾点标识</td>'+
													'</tr>'+
												'</table>'+
											'</div>'+
											'</div>';
	geologicHazardQueryDlg = $.dialog({
		title: '基本情况查询',
		content: geologicHazardDlgHtml,
		dlgDivId: "geologicQueryDiv",
		resize: false,
		max: false,
		left:"250px",
		top:'100px',
		width:'340px',
		height:'200px',
		min:onGeoQueryDlgMin,
		init:function(){
			$("#geohazardBtn").click(onQueryGeoHazardFunction);
		},
		close:onGeoHazardQueryDlgCloseFunc
	});
}

function onGeoQueryDlgMin(){
	minDlgByAnimate(geologicHazardQueryDlg);
}

function onGeoHazardQueryDlgCloseFunc(){
	geologicHazardQueryDlg = null;
}

function onQueryGeoHazardFunction(){
	var startTime = $("#yjdc3jbxxTimeInputForm").val();
	var endTime = $("#yjdc3jbxxTimeInputTo").val();
	var name = $("#yjdc3jbxxNameInputTo").val();
	var obj = {startTime:startTime,endTime:endTime,name:name};
	var url = "queryYjdc3jbxxBenji.shtml";
	$.post(url,obj,onQueryGeologicHazardResult);
}

function onQueryGeologicHazardResult(res){
	$(".yjdc3ResultTr").remove();
	res = eval("("+res+")");
	if(res.length>0){
		for(var i = 0;i<res.length;i++){
			
			var name = res[i][1];
			var zhType = getOperTypeZhdByCode(res[i][2]);
			
			var resStr =  '<tr class="yjdc3ResultTr">'+
			'<td class="queryTd">'+(i+1)+'</td><td class="queryClickForGeo" id="'+i+'" style="cursor:pointer;">'+name+'</td><td class="queryTd">'+zhType+'</td>'+
			'</tr>';
			$("#queryYjdc3JbxxResultTable").append(resStr);

		}
		$(".queryClickForGeo").click(function(evt){
			var index = evt.currentTarget.id;
			onClickOneGeoHazard(res[index][0],res[index][1],res[index][2]);
		});
	}else{
		alert("没有查询到任何信息!");
	}
}

function onClickOneGeoHazard (tybh,name,zdType){
	clickName = name;
	var url = "queryYjdc3jbxxByTybh.shtml";
	var startTime = $("#yjdc3jbxxTimeInputForm").val();
	var endTime = $("#yjdc3jbxxTimeInputTo").val();
	var data = {
			startTime:startTime,
			endTime:endTime,
			tybh:tybh,
			biaoshi:zdType
	};
	global_sketch_geoCode = tybh;
	global_sketch_geoCodeType = zdType;
	$.post(url,data,onQueryGeoHazardInfoCallBack);
}

function onQueryGeoHazardInfoCallBack(result){
	var result = eval("("+result+")");
	//将查询到的结果，通过对话框展示出来
	initNewSketchDig(result);
}

function initNewSketchDig(res){
	if(global_vector_layer){
		map.removeLayer(global_vector_layer);
		global_vector_layer = null;
	}
	if(newSketchDig){
		//newSketchDig=null;
	}
	var newSketchDigHTML= '<div style="width:340px;height:200px;font-size:11px;font-family:微软雅黑;position:absolute;left:15px;top:40px;">'+
							'<label style="color: red;">请您选择应急调查的时间:</label><select style="width:150px;" id="chooseTime"></select>'+
							'<div id="div_new_sketch" style="margin-top:60px;margin-left:10px">'+
								'<input type="button" value="添加线" style="margin-right:20px" id="btn_line_add">'+
								'<input type="button" value="添加点" style="margin-right:20px" id="btn_pnt_add">'+
						
								'<input type="button" value="删除" style="margin-right:20px" id="btn_del">'+
							'</div>'+
							'<div style="margin-top:50px">'+
								'<input type="button" value="保存" style="margin-left:260px" id="btn_newsketch_save">'+
							'</div>'+
							'</div>';
	newSketchDig = $.dialog({
		title: '新增素描',
		content: newSketchDigHTML,
		dlgDivId: "newSketchDigDiv",
		resize: false,
		max: false,
		left:"250px",
		top:'100px',
		width:'340px',
		height:'200px',
		min:onNewSketchDlgMin,
		
		init:function(){
				$("#fanzaoDiv td").css("border","1px solid #D8DBE0");
				//初始化完毕，加载时间选择列表
				var optionStr = '<option selected="selected" value="">请选择调查时间</option>';
				
				for(var i = 0;i<res.length;i++){
					var time = res[i].yjdc01270;
					var year = Number(time.year)+1900;
					var month = (Number(time.month)+1)<10?"0"+(Number(time.month)+1):(Number(time.month)+1);
					var day = Number(time.date<10)?"0"+time.date:time.date;
					var hours = Number(time.hours<10)?"0"+time.hours:time.hours;
					var minutes = Number(time.minutes<10)?"0"+time.minutes:time.minutes;
					var seconds = Number(time.seconds<10)?"0"+time.seconds:time.seconds;
					var timeStr  = year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
					optionStr = optionStr + '<option value="'+res[i].yjdc01270.time+'">'+timeStr+'</option>';
				}
				
				$("#chooseTime").html("");
				
				$("#btn_line_add").click(onAddLine);
				$("#btn_pnt_add").click(onAddPnt);
				$("#btn_del").click(onDeleteFeature);
				$("#btn_newsketch_save").click(onNewSketchSave);
				
				$("#chooseTime").append(optionStr);

//				$("#chooseTime").change( function(){
//					var index = $("#chooseTime").val();
//					if(index=="")
//						return;
//					giveValueToEdit(res[index]);
//				})
				
				$("#editInsertButton").click(editInsertClickFunction);
				$("#geohazardBtn").click(onQueryGeoHazardFunction);
		},
		close:oNewSketchClose
	});
}

function oNewSketchClose(){
	
	if(global_vector_layer)
	{
		//////add by cuiyi 20130227
		if(global_vector_layer.my_control){
			global_vector_layer.my_control.deactivate();
			map.removeControl(global_vector_layer.my_control);
		}
		global_vector_layer.removeAllFeatures();
		global_vector_layer =null;
	}
	newSketchDig=null;
}

function onNewSketchDlgMin(){
	minDlgByAnimate(newSketchDig);
}

function onNewSketchSave(){
	var geoTime=$("#chooseTime").val();
	if( geoTime== ""){
		alert("请选择一个时间");
		return;
	}
	if(!global_vector_layer){
		alert("请先绘制要素");
		return;
	}
	var features = global_vector_layer.features;
	var featureArray = processFeatureToData(features);
	var s= JSON.stringify(featureArray);
	var data = {
			geoCode:global_sketch_geoCode,
			geoCodeType:global_sketch_geoCodeType,
			features:s,
			time:geoTime
	}
	var url ="new_sketch.shtml";
	
	$.post(url,data,onPostNewSKetchToServer);
}

function processFeatureToData(features){
	var featuresArray = new Array();
	for(var i=0;i<features.length;i++){
		var type;
		var geometryString;
		if(features[i].geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){
			type=0;
			geometryString = features[i].geometry.toShortString();
		}
		else{
			type=1;
			geometryString = features[i].geometry.getComponentsString();
		}
		var obj = {
				style:features[i].style,
				renderIntent:features[i].renderIntent,
				geometry:geometryString,
				type:type
		}
		featuresArray.push(obj);
	}
	return featuresArray;
}

function onPostNewSKetchToServer(data){
	if(data=="true"){
		if(!global_vector_layer)
			return ;
		
		map.removeLayer(global_vector_layer);
		global_vector_layer = null;
		alert("添加成功");
	}
	else{
			alert("添加失败");
	}
}

function onAddPnt(){
	if(!global_vector_layer){
		global_vector_layer =  new OpenLayers.Layer.Vector('SketchLayer');
		map.addLayer(global_vector_layer);
	}
	var layer = global_vector_layer;
	var control = new OpenLayers.Control.DrawFeature(
			layer,
			OpenLayers.Handler.Point);
	map.addControl(control);
	control.activate();
	control.featureAdded = onPntAdded;
	global_vector_layer.my_control = control;
	document.getElementById("div_new_sketch").disabled=true;
}

function onPntAdded(event){
    var geometryString = event.geometry.toShortString();
	var obj = {
			style:event.style,
			renderIntent:event.renderIntent,
			geometry:geometryString,
			type:0
	}
	global_features_add.push(obj);
	global_vector_layer.my_control.deactivate();
	map.removeControl(global_vector_layer.my_control);
	document.getElementById("div_new_sketch").disabled=false;
}

function onAddLine(){
	if(!global_vector_layer){
		global_vector_layer =  new OpenLayers.Layer.Vector('SketchLayer');
		map.addLayer(global_vector_layer);
	}
	var layer = global_vector_layer;
	var control = new OpenLayers.Control.DrawFeature(
			layer,
			OpenLayers.Handler.Path);
	map.addControl(control);
	control.activate();
	control.featureAdded = onLineAdded;
	global_vector_layer.my_control = control;
	document.getElementById("div_new_sketch").disabled=true;
}

function onLineAdded(event){
    var geometryString = event.geometry.getComponentsString();
	var obj = {
			style:event.style,
			renderIntent:event.renderIntent,
			id:event.id,
			geometry:geometryString,
			type:1
	}
	global_features_add.push(obj);
	global_vector_layer.my_control.deactivate();
	map.removeControl(global_vector_layer.my_control);
	document.getElementById("div_new_sketch").disabled=false;
}

function onDeleteFeature(){
	document.getElementById("div_new_sketch").disabled=true;
	if(!global_vector_layer){
		alert("当前没有素描");
		return;
	}
	 var selectControl=new OpenLayers.Control.SelectFeature(
			 global_vector_layer,
             {
                 clickout: true, toggle: false,
                 multiple: false, hover: false,
                 toggleKey: "ctrlKey", // ctrl key removes from selection
                 multipleKey: "shiftKey", // shift key adds to selection
                 box: false
             }
	 )
	 onSelectFeature.temp = selectControl;
	 selectControl.onSelect = onSelectFeature;
	   var highlightCtrl = new OpenLayers.Control.SelectFeature(global_vector_layer, {
            hover: true,
            highlightOnly: true,
            renderIntent: "temporary"
        });
	 
	 map.addControls([selectControl]);
//	 highlightCtrl.activate();
	 selectControl.activate();
	 
	
//	 global_vector_layer.events.on({
//         'featureselected':
//	 });
}

function onSelectFeature(feature){
//	 	 var isDelete=confirm("是否删除该要素？");
//	 	 if(isDelete){
	document.getElementById("div_new_sketch").disabled=false;
	 	      global_vector_layer.removeFeatures([feature]);
//	 	 }
	 	var realFeature = feature;
	 	if(!realFeature.fid){
	 		deleteFeatuesGlobalAddArray(realFeature);
	 	}
	 	else{
	 		global_features_del.push(realFeature.fid.toString());
	 	}
	 	onSelectFeature.temp.deactivate();
//     	highlightCtrl.deactivate();
    	map.removeControl(onSelectFeature.temp);
//    	map.removeControl(highlightCtrl);
     }

function deleteFeatuesGlobalAddArray(feature){
	if(global_features_add !=null){
		
		global_features_add=$.grep(global_features_add,function(value,i){
			 if(value.id == feature.id){
				 return false;
			 }
			 else
				 return true;
		})
	}
}



